package com.geek.novel.view.loading;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

/**
 * loading弹出框样式
 * @Author Hydra
 * @Date 2022/5/30 13:13
 */
public class LoadingDialogUtil {

    /**弹框打开的码值*/
    private final int HANDLER_CODE_DIALOG_SHOW = 1;
    /**弹框关闭的码值*/
    private final int HANDLER_CODE_DIALOG_CLOSE = 0;

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case HANDLER_CODE_DIALOG_SHOW:
                    if(!loadingDialog.isShowing()){
                        loadingDialog.show();
                    }
                    break;
                case HANDLER_CODE_DIALOG_CLOSE:
                    if(loadingDialog.isShowing()){
                        loadingDialog.dismiss();
                    }
                    break;
            }
        }
    };

    private ShapeLoadingDialog loadingDialog;

    private LoadingDialogUtil(){
    }

    /**初始化loading弹框*/
    public void init(Context context){
        ShapeLoadingDialog.Builder builder = new ShapeLoadingDialog.Builder(context);
        loadingDialog = builder.loadText("加载中...").build();
    }

    /**设置加载文本*/
    public LoadingDialogUtil setText(String text){
        if(loadingDialog != null){
            loadingDialog.setText(text);
        }
        return this;
    }

    private static LoadingDialogUtil instance;
    public static LoadingDialogUtil getInstance(){
        if(instance == null){
            instance = new LoadingDialogUtil();
        }
        return instance;
    }

    /**显示loading弹框*/
    public void showLoading(String text){
        setText(text);
        handler.sendEmptyMessage(HANDLER_CODE_DIALOG_SHOW);
    }

    /**关闭loading弹框*/
    public void dismiss(){
        handler.sendEmptyMessage(HANDLER_CODE_DIALOG_CLOSE);
    }

}
